package com.tanhua.dubbo.async;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 异步处理-循环往好友时间线表插入数据
 */
@Component
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 循环插入时间线表方法
     */
    @Async
    public void addTimeLines(Long loginUserId, Movement movement){
        //2查询好友表获取所有好友ids
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(loginUserId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        log.debug("**********查询好友表{}**********",friendList.toString());
        //3往好友时间线表插入数据
        if(!CollectionUtils.isEmpty(friendList)){
            for (Friend friend : friendList) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(movement.getId());//动态id(保存动态表主键id)
                movementTimeLine.setUserId(loginUserId);//发布动态用户id
                movementTimeLine.setFriendId(friend.getFriendId());//可见好友id
                movementTimeLine.setCreated(movement.getCreated());
                mongoTemplate.insert(movementTimeLine);
            }
        }
        log.debug("*********循环插入时间线表数据成功了**********");
    }
}
